function p = pfs_GetPropertyNr(hfile, idx)
% PFS::GetPropertyNr  - read POIFS property from POIFS file
%
% FORMAT:       p = pfs.GetPropertyNr(idx)
%
% Input fields:
%
%       idx         the index of the POIFS file (1-based)
%
% Output fields:
%
%       p           the obtained property

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'pfs') || ...
    numel(idx) ~= 1 || ...
    isinf(idx) || ...
    isnan(idx) || ...
    idx < 1
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid argument in call.' ...
    );
end
sc = bvqxfile_getscont(hfile.L);
bc = sc.C;

% try opening file
fid = fopen(sc.F, 'r', 'ieee-le');
if fid < 1
    error( ...
        'BVQXfile:FileOpenError', ...
        'Error opening POIFS file.' ...
    );
end
pblidx = bc.FirstPropertyBlock;
oidx = idx;
while (idx > bc.PropertiesPerBlock)
    pblidx = bc.BAT(pblidx);
    if pblidx < 1
        fclose(fid);
        error( ...
            'BVQXfile:POIFSError', ...
            'BAT link error in POIFS file.' ...
        );
    end
    idx = idx - bc.PropertiesPerBlock;
end
ppos = bc.LargeBlockSize * double(pblidx) + (idx - 1) * 128;
fseek(fid, ppos, -1);
if ftell(fid) ~= ppos
    fclose(fid);
    error( ...
        'BVQXfile:POIFSError', ...
        'Error seeking to property.' ...
    );
end
p = cell2struct(cell(1, 1, 15), ...
    {'Name', 'NameSize', 'Type', 'Color', ...
     'Previous', 'Next', 'FirstChild', ...
     'CLSID', 'UserFlags', 'Created', 'Modified', ...
     'FirstBlock', 'Size', 'BlockAccess', 'Reserved7c'}, 3);
p.Name = fread(fid, [1, 32], 'uint16=>uint16');
p.NameSize = floor(fread(fid, [1, 1], 'uint16=>double') / 2) - 1;
p.Name = char(p.Name(1:p.NameSize));
p.Type = fread(fid, [1, 1], 'uint8=>double');
p.Color = fread(fid, [1, 1], 'uint8=>double');
p.Previous = fread(fid, [1, 1], 'int32=>double') + 1;
p.Next = fread(fid, [1, 1], 'int32=>double') + 1;
p.FirstChild = fread(fid, [1, 1], 'int32=>double') + 1;
p.CLSID = fread(fid, [1, 16], 'uint8=>uint8');
p.UserFlags = fread(fid, [1, 1], 'int32=>int32');
p.Created = fread(fid, [1, 1], 'int64=>int64');
p.Modified = fread(fid, [1, 1], 'int64=>int64');
if p.Created(1) ~= 0
    p.Created = datestr(584389 + double(p.Created) / 8.64e11);
end
if p.Modified ~= 0
    p.Modified = datestr(584389 + double(p.Modified) / 8.64e11);
end
p.FirstBlock = fread(fid, [1, 1], 'int32=>int32') + 1;
p.Size = fread(fid, [1, 1], 'int32=>double');
if p.Size >= bc.SBATThresholdSize
    p.BlockAccess = 'BAT';
else
    p.BlockAccess = 'SBAT';
end
p.Reserved7c = fread(fid, [1, 1], 'uint32=>double');
fclose(fid);

% for Root for Access to BAT
if oidx == 1
    p.BlockAccess = 'BAT';
end
